<script>
import BookFrom from "../../components/book/BookForm.vue";
import BookApi from "../../api/book";

export default {
  components: {
    BookFrom
  },
  data() {
    return {
      book: {},
      isNotFetch: true
    };
  },
  methods: {
    async fetchDouban() {
      try {
        let isbn = this.book.isbn;
        this.book = {};
        const api = new BookApi();
        let res1 = await api.findByIsn(isbn);
        if (res1.data.id) {
          this.$myMessageBox(`《${res1.data.title}》书库已存在！`);
          this.$router.push({ name: "book-detail", params: { id: res1.data.id } });
        } else {
          let res2 = await api.fetchDouban(isbn);
          this.$myMessageBox(res2.msg);
          if (res2.code === 400) {
            this.book = {};
            this.isNotFetch = true;
          } else {
            this.book = res2.data;
            console.log(this.book);
          }
        }
      } catch (err) {
        console.error(err);
        this.$myMessageBox("应用服务器访问错误！");
      }
    },
    async bookSave() {
      if (this.book.title && this.book.isbn) {
        try {
          const api = new BookApi();
          let res = await api.add(this.book);
          console.log(res);
          if (res.code === 201) {
            this.$myMessageBox(res.msg);
            this.$router.push({ name: "book-list" });
          }
        } catch (err) {
          console.error(err);
          this.$myMessageBox("应用服务器访问错误！");
        }
      } else {
        this.$myMessageBox("书名与ISBN号信息不完整！");
      }
    }
  },
  watch: {
    book: {
      handler(newValue) {
        let isbn = newValue.isbn;
        let regex13 = /^978\d{10}$/;
        let regex10 = /^\d{10}$/;
        if (isbn) {
          if (
            (isbn.length === 10 && regex10.test(isbn)) ||
            (isbn.length === 13 && regex13.test(isbn))
          ) {
            this.isNotFetch = false;
          } else {
            this.isNotFetch = true;
          }
        }
      },
      deep: true
    }
  }
};
</script>

<template>
  <div class="book-add w80">
    <div class="header">
      <h2>新增书籍</h2>
      <p>
        <a
          class="button"
          :class="{ disabled: isNotFetch }"
          href="javascript:void(0)"
          @click="fetchDouban"
          >从豆瓣读书采集书籍信息</a
        >
        <a class="button" href="javascript:void(0)" @click="$goBack">返回</a>
      </p>
    </div>
    <div class="block">
      <book-from v-model="book" @book-save="bookSave"></book-from>
    </div>
  </div>
</template>

<style scoped></style>
